package cipher

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
)

/**
公钥封装接口
只用用来加密和验签
 */
type RsaPublicCipher struct {
	pubKey *rsa.PublicKey
}


func (r *RsaPublicCipher)SetPublicKey(publicKey []byte)(err error){

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return
	}
	r.pubKey = pubInterface.(*rsa.PublicKey)

	return

}
func (r *RsaPublicCipher)Encrypt(src []byte) (dst []byte, err error){
	if r.pubKey == nil{
		err = errors.New("RsaPublicCipher.Encrypt没有设置公钥")
		return
	}
	return rsa.EncryptPKCS1v15(rand.Reader, r.pubKey, src)
}
func (r *RsaPublicCipher)VerifySign(src,sig []byte)(isOk bool, err error){
	if r.pubKey == nil{
		err = errors.New("RsaPublicCipher.Encrypt没有设置公钥")
		return
	}
	h := sha256.Sum256(src)
	err = rsa.VerifyPKCS1v15(r.pubKey,crypto.SHA256,h[:],sig)
	if err != nil {
		return false,err
	}
	return true,nil
}


